package com.wosiliujing.learning.config;

import com.wosiliujing.learning.properties.DefaultHikariDataSourceProperties;
import com.wosiliujing.learning.properties.DynamicDataSourceProperties;
import com.wosiliujing.learning.support.DataSourceConstants;
import com.zaxxer.hikari.HikariDataSource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.transaction.ChainedTransactionManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘靖
 * @date 2019-10-30 16:04
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class DynamicDataSourceConfig implements TransactionManagementConfigurer {
    private final Map<Object, Object> dataSourceMap = new HashMap<>(8);
    private final DefaultHikariDataSourceProperties dataSourceProperties;
    private final DynamicDataSourceProperties dynamicDataSourceProperties;

    @Bean("dynamicDataSource")
    public  DynamicDataSource dataSource(){
        HikariDataSource defaultDataSource = DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .password(dataSourceProperties.getPassword())
                .username(dataSourceProperties.getUsername())
                .url(dataSourceProperties.getUrl()).build();
        dataSourceMap.put(DataSourceConstants.DS_DEFAULT,defaultDataSource);
        dynamicDataSourceProperties.getDataSource().forEach((key,dataSource) -> {
           HikariDataSource hikariDataSource = DataSourceBuilder.create()
                   .type(HikariDataSource.class)
                   .password(dataSource.getPassword())
                   .username(dataSource.getUsername())
                    .url(dataSource.getUrl()).build();
            dataSourceMap.put(key, hikariDataSource);
        });
        DynamicDataSource dds = new DynamicDataSource();
        dds.setDefaultTargetDataSource(defaultDataSource);
        dds.setTargetDataSources(dataSourceMap);
        dds.afterPropertiesSet();
        return dds;
    }


    @Bean
    public PlatformTransactionManager txManager() {
        DataSourceTransactionManager transactionManager
                = new DataSourceTransactionManager(dataSource());
        return new ChainedTransactionManager(transactionManager);
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager();
    }


}
